﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ScriptEditor.Commands;
using LitJson;
using System.IO;
using System.Collections.Specialized;
using System.Globalization;
using System.Text.RegularExpressions;

namespace ScriptEditor
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ShowWindow : Window
    {
        Editor editor;
        Script script = new Script();
        Command copy = null;
        string filePath = "";
        public ShowWindow()
        {
            InitializeComponent();
            CommandList.ItemsSource = script;
            //testCode();
        }
        //显示编辑窗口
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            editor = new Editor();
            editor.Show();
            editor.ShowInTaskbar = false;
            editor.Owner = this;
        }
        public void testCode()
        {
            script.Add(new Command());
            script.Add(new Command());
            script.Add(new Command_AddBlog());
            script.Add(new Command_ActionStart());
            //script.Add(new Command_ShowChar("111", "222", 1, new Vector3 { x = 1, y = 2, z = 3 }, new Vector2 { x = 1, y = 2 }, "12", 1, 2, 3, 4, false));
        }

        //指令被选中
        private void CommandList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = ((ListBox)sender).SelectedIndex;
            Command command;
            if (index != -1)
            {
                editor.SetCommandUI(script.GetCommandUIAt(index,out command),script,index);
                editor.SubmitBox.Visibility = Visibility.Visible;
                Title = "BrokenDelusionMod  " + "选中序号：" + index.ToString() + " " + "剧本：" + filePath;
            }
            else
            {
                editor.SetCommandUI(new Dictionary<string, CommandUI>(), script, index);
                editor.SubmitBox.Visibility = Visibility.Hidden;
                Title = "BrokenDelusionMod  " + " "+"剧本：" + filePath;
            }
        }

        //显示编辑框
        private void MenuItem_Click_ShowEditor(object sender, RoutedEventArgs e)
        {
            editor.Show();
        }

        //关闭程序
        private void MenuItem_Click_Close(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        //载入剧本
        private void MenuItem_Click_LoadScript(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.Filter = "剧本文件|*.json";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = Path.GetFullPath(dialog.FileName);
                JsonData json = JsonMapper.ToObject(File.ReadAllText(filePath));
                script.Clear();
                for (int i = 0; i < json.Count; i++)
                {
                    //创建指令时根据内容自动转换指令类型
                    script.Add((Command)(new Command(json[i])).ConvertCommand());
                }
            }
        }

        //右键菜单
        private void CommandContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            //是否存在选中指令
            CommandContextDelete.IsEnabled = CommandList.SelectedIndex != -1;
            CommandContextMoveUp.IsEnabled = CommandList.SelectedIndex != -1 && CommandList.SelectedIndex != 0;
            CommandContextMoveDown.IsEnabled = CommandList.SelectedIndex != -1 && CommandList.SelectedIndex != CommandList.Items.Count - 1;
            CommandContextCopy.IsEnabled= CommandList.SelectedIndex != -1;
            CommandContextPaste.IsEnabled = copy != null;
        }
        //删除选中指令
        private void CommandContextDelete_Click(object sender, RoutedEventArgs e)
        {
            script.RemoveAt(CommandList.SelectedIndex);
        }
        //跳转至序号
        private void JumpIndex_Click(object sender, RoutedEventArgs e)
        {
            int index = 0;
            bool isIndex = int.TryParse(JumpIndexText.Text, out index);
            if (isIndex && index >= 0 && index <= script.Count)
            {
                CommandList.SelectedIndex = index;
                ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(CommandList, 0), 0);
                int verticalOffset = (int)scrollViewer.VerticalOffset;
                if (index < verticalOffset)
                {
                    verticalOffset = index;
                }
                else if (index > (int)(scrollViewer.ViewportHeight + verticalOffset - 1))
                {
                    verticalOffset = index + 1 - (int)scrollViewer.ViewportHeight;
                }
                scrollViewer.ScrollToVerticalOffset(verticalOffset);
            }
            else
            {
                MessageBox.Show("输入的序号不合法！");
            }
        }

        //跳转至对应ID
        private void JumpID_Click(object sender, RoutedEventArgs e)
        {
            string target = JumpIDText.Text;
            int index = 0;
            foreach(Command c in script)
            {
                if (c.id == target)
                {
                    CommandList.SelectedIndex = index;
                    ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(CommandList, 0), 0);
                    int verticalOffset = (int)scrollViewer.VerticalOffset;
                    if (index < verticalOffset)
                    {
                        verticalOffset = index;
                    }
                    else if (index > (int)(scrollViewer.ViewportHeight + verticalOffset - 1))
                    {
                        verticalOffset = index + 1 - (int)scrollViewer.ViewportHeight;
                    }
                    scrollViewer.ScrollToVerticalOffset(verticalOffset);
                    return;
                }
                index++;
            }
            MessageBox.Show("未找到输入的ID！");
        }

        //另存为剧本
        private void MenuItem_Click_SaveOther(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.Filter = "剧本文件|*.json";
            dialog.CheckFileExists = false;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = Path.GetFullPath(dialog.FileName);
                File.WriteAllText(filePath, Command.writeSum(script).ToJson());
            }
        }

        //保存剧本
        private void MenuItem_Click_Save(object sender, RoutedEventArgs e)
        {
            if (filePath != "")
            {
                File.WriteAllText(filePath, Command.writeSum(script).ToJson());
            }
            else
            {
                System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
                dialog.Filter = "剧本文件|*.json";
                dialog.CheckFileExists = false;
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    filePath = Path.GetFullPath(dialog.FileName);
                    File.WriteAllText(filePath, Command.writeSum(script).ToJson());
                }
            }
        }

        //关于按钮
        private void About_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("妄想破绽剧本编辑器\nby:Mengluu 懒惰熊猫\n联系方式：734542326@qq.com");
        }

        //插入指令
        private void CommandContextInsert_Click(object sender, RoutedEventArgs e)
        {
            SelectCommandUI select = new SelectCommandUI();
            select.ShowDialog();
            if (select.OK)
            {
                int index = CommandList.SelectedIndex + 1;
                script.Insert(index, select.CreateCommand);
                CommandList.SelectedIndex = index;
            }
        }

        //指令上移
        private void CommandContextMoveUp_Click(object sender, RoutedEventArgs e)
        {
            int index = CommandList.SelectedIndex;
            Command tmp = script[index];
            script.RemoveAt(index);
            script.Insert(index - 1, tmp);
            CommandList.SelectedIndex = index - 1;
        }
        //指令下移
        private void CommandContextMoveDown_Click(object sender, RoutedEventArgs e)
        {
            int index = CommandList.SelectedIndex;
            Command tmp = script[index];
            script.RemoveAt(index);
            script.Insert(index + 1, tmp);
            CommandList.SelectedIndex = index + 1;
        }
        //复制指令
        private void CommandContextCopy_Click(object sender, RoutedEventArgs e)
        {
            copy = script[CommandList.SelectedIndex];
        }
        //粘贴指令
        private void CommandContextPaste_Click(object sender, RoutedEventArgs e)
        {
            int index = CommandList.SelectedIndex + 1;
            script.Insert(index, (Command)copy.ConvertCommand());
            CommandList.SelectedIndex = index;
        }

        //搜索指令
        struct SearchStruct
        {
            public int index;
            public string str;
            public override string ToString()
            {
                return str;
            }
        }
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            SearchResult.Items.Clear();
            if (Search.Text == "")
            {
                return;
            }
            for(int i=0;i<script.Count;i++)
            {
                Command command = script[i];
                string json = Regex.Unescape(command.writeJson().ToJson());
                string[] Keys = Search.Text.Split(new char[] { ' ' });
                bool flag = true;
                foreach(string key in Keys)
                {
                    flag &= json.Contains(key);
                }
                if (flag)
                {
                    int findPos = json.IndexOf(Keys[0]);
                    SearchResult.Items.Add(new SearchStruct { index = i, str = json.Substring((findPos - 5 < 0) ? 0 : findPos - 5, 40) });
                }
            }
        }

        //根据搜索跳转
        private void SearchResult_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SearchResult.SelectedItem != null)
            {
                int index= ((SearchStruct)SearchResult.SelectedItem).index;
                CommandList.SelectedIndex = index;
                ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(CommandList, 0), 0);
                int verticalOffset = (int)scrollViewer.VerticalOffset;
                if (index < verticalOffset)
                {
                    verticalOffset = index;
                }
                else if (index > (int)(scrollViewer.ViewportHeight + verticalOffset - 1))
                {
                    verticalOffset = index + 1 - (int)scrollViewer.ViewportHeight;
                }
                scrollViewer.ScrollToVerticalOffset(verticalOffset);
            }
        }

        //输出最终Mod文件
        private void MenuItem_Click_Mod(object sender, RoutedEventArgs e)
        {
            OutputUI output = new OutputUI();
            output.ShowDialog();
            if (output.IsOk)
            {
                Console.WriteLine(output.modName);
                Console.WriteLine(output.modAuthor);
                Console.WriteLine(output.modSign);
                Console.WriteLine(output.modDescription);
                Console.WriteLine(output.modEntry);
                foreach(string file in output.modFile)
                {
                    Console.WriteLine(file);
                }
                System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
                dialog.Filter = "Mod文件|*.mod";
                dialog.CheckFileExists = false;
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    filePath = Path.GetFullPath(dialog.FileName);
                    JsonData json = new JsonData();
                    json["ModName"] = output.modName;
                    json["ModAuthor"] = output.modAuthor;
                    json["ModSign"] = output.modSign;
                    json["ModDescription"] = output.modDescription;
                    json["ModEntry"] = Path.GetFileNameWithoutExtension(output.modEntry);
                    json["ModFile"] = new JsonData();
                    foreach (string file in output.modFile)
                    {
                        JsonData script = JsonMapper.ToObject(File.ReadAllText(Path.GetFullPath(file)));
                        json["ModFile"][Path.GetFileNameWithoutExtension(file)] = script;
                    }
                    File.WriteAllText(filePath, json.ToJson());
                }
            }
        }
    }
}
